package cn.edu.zjut.mina.service.impl;

import java.util.Date;

import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.zjut.mina.bean.StandardFormat;
import cn.edu.zjut.mina.po.DepositRoomCard;
import cn.edu.zjut.mina.po.UserInfo;
import cn.edu.zjut.mina.protocal.JMessageProtocalRes;
import cn.edu.zjut.mina.protocal.ProtocalRegulation;
import cn.edu.zjut.mina.repository.DepositRoomCardRepository;
import cn.edu.zjut.mina.repository.UserInfoRepository;
import cn.edu.zjut.mina.service.IDepositService;
import cn.edu.zjut.mina.util.GsonUtils;
import cn.edu.zjut.mina.util.ResultInfoConstUtils;
import cn.edu.zjut.mina.util.UserMap;

@Service("depositService")
public class DepositServiceImpl implements IDepositService{
	@Autowired
	private UserInfoRepository userInfoRepository;
	
	@Autowired
	private DepositRoomCardRepository depositRoomCardRepository;
	
	private final UserMap userMap = UserMap.getInstance();
	
	@Transactional(rollbackFor=Exception.class)
	public String depositroomcard(String unionid, int roomCardNum, int depositmoney) {
		// TODO Auto-generated method stub
		String datasHttp = "";
		StandardFormat outJsonHttp = new StandardFormat();
		UserInfo user = userInfoRepository.findByUnionid(unionid);
		if (user == null) {
			outJsonHttp.resultInfo = "充值失败";
			datasHttp = GsonUtils.beanToJson(outJsonHttp).trim();
			return datasHttp;
		}
		user.setRoomCardNum(user.getRoomCardNum() + roomCardNum);
		DepositRoomCard depositRoomCard = new DepositRoomCard();
		depositRoomCard.setDepositmoney(depositmoney);
		depositRoomCard.setDepositRoomCard(roomCardNum);
		depositRoomCard.setDepositRoomCardTime(new Date());
		depositRoomCard.setNickName(user.getNickName());
		depositRoomCard.setUserId(user.getUserId());
		depositRoomCard.setUnionid(unionid);
		depositRoomCardRepository.save(depositRoomCard);
		userInfoRepository.save(user);
		
		if (userMap.get(user.getUserId()) != null) {
			//userMap.get(user.getUserId()).user.setRoomCardNum(user.getRoomCardNum());//更新缓存中的房卡数(由于这部分别人也在写，先去数据库里找吧)
			//推送消息
			JMessageProtocalRes res = new JMessageProtocalRes();
			
			StandardFormat outJson = new StandardFormat();
			String datas;
			//返回文字信息
			outJson.result = true;
			outJson.userId = user.getUserId();
			outJson.roomcardnum = user.getRoomCardNum();//房卡数
			
			datas = GsonUtils.beanToJson(outJson).trim();
			res.setContent(datas);
			res.setResultCode(ProtocalRegulation.PUSHROOMCARD);
			IoSession session = userMap.get(user.getUserId()).session;
			session.write(res);
		}
		outJsonHttp.resultInfo = "充值成功";
		datasHttp = GsonUtils.beanToJson(outJsonHttp).trim();
		return datasHttp;
	}
	
	
}
